package com.sj.hh.ui.article;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatEditText;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.rong.mbt.personal.activity.base.PBaseActivity;
import com.rong.mbt.personal.bean.base.BaseBean;
import com.rong.mbt.personal.http.OkHttpManager;
import com.rong.mbt.personal.http.UrlApi;
import com.rong.mbt.personal.http.callback.JsonCallback;
import com.rong.mbt.personal.utils.ToastUtil;
import com.sj.friendcircle.common.router.RouterList;
import com.sj.friendcircle.lib.entity.ImageInfo;
import com.sj.friendcircle.lib.helper.AppFileHelper;
import com.sj.friendcircle.lib.helper.PermissionHelper;
import com.sj.friendcircle.lib.interfaces.OnPermissionGrantListener;
import com.sj.friendcircle.lib.manager.compress.CompressManager;
import com.sj.friendcircle.lib.manager.compress.OnCompressListener;
import com.sj.friendcircle.lib.utils.ToolUtil;
import com.sj.friendcircle.ui.helper.PhotoHelper;
import com.sj.friendcircle.ui.imageloader.ImageLoadMnanger;
import com.sj.friendcircle.ui.util.UIHelper;
import com.sj.friendcircle.ui.widget.imageview.PreviewImageView;
import com.sj.friendcircle.ui.widget.popup.PopupProgress;
import com.sj.friendcircle.ui.widget.popup.SelectPhotoMenuPopup;
import com.sj.hh.R;
import com.sj.hh.ui.ActivityLauncher;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = RouterList.PublishArticlesActivity.path)
@SuppressLint("NewApi")
public class PublishArticlesActivity extends PBaseActivity {


    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.iv_right)
    View ivRight;
    @BindView(R.id.ll_right_menu)
    LinearLayout llRightMenu;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.ll_right_text)
    LinearLayout llRightText;
    @BindView(R.id.edit_title)
    AppCompatEditText editTitle;
    @BindView(R.id.edit_content)
    AppCompatEditText editContent;
    @BindView(R.id.id_editor_detail_font_count)
    TextView idEditorDetailFontCount;
    @BindView(R.id.preview_image)
    PreviewImageView previewImage;
    @BindView(R.id.publish)
    Button publish;

    private SelectPhotoMenuPopup mSelectPhotoMenuPopup;
    private PermissionHelper permissionHelper;
    private PopupProgress mPopupProgress;
    private List<ImageInfo> selectedPhotos = new ArrayList<>();

    @Override
    public void initView() {
        super.initView();

        txtTitle.setText("发布");

        AppFileHelper.initStroagePath(this);
        permissionHelper = new PermissionHelper(this);
        initListener();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_publish_articles;
    }

    private void initListener() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            previewImage.setOnAddPhotoClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    permissionHelper.requestPermission(new OnPermissionGrantListener() {
                        @Override
                        public void onPermissionGranted(PermissionHelper.Permission... grantedPermissions) {
                            showSelectPhotoPopup();
                        }

                        @Override
                        public void onPermissionsDenied(PermissionHelper.Permission... deniedPermissions) {

                        }
                    }, PermissionHelper.Permission.WRITE_EXTERNAL_STORAGE, PermissionHelper.Permission.READ_EXTERNAL_STORAGE);
                }
            });

            previewImage.setDatas(selectedPhotos, new PreviewImageView.OnLoadPhotoListener<ImageInfo>() {
                @Override
                public void onPhotoLoading(int pos, ImageInfo data, @NonNull ImageView imageView) {
                    ImageLoadMnanger.INSTANCE.loadImage(imageView, data.getImagePath());
                }
            });
        }
    }

    private void showSelectPhotoPopup() {
        if (mSelectPhotoMenuPopup == null) {
            mSelectPhotoMenuPopup = new SelectPhotoMenuPopup(this);
            mSelectPhotoMenuPopup.setOnSelectPhotoMenuClickListener(new SelectPhotoMenuPopup.OnSelectPhotoMenuClickListener() {
                @Override
                public void onShootClick() {
                    PhotoHelper.fromCamera(this, false);
                }

                @Override
                public void onAlbumClick() {
                    ActivityLauncher.startToPhotoSelectActivity(PublishArticlesActivity.this, RouterList.FriendCircleBg.requestCode);
                }
            });
        }
        mSelectPhotoMenuPopup.showPopupWindow();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RouterList.FriendCircleBg.requestCode && resultCode == RESULT_OK) {
            List<ImageInfo> result = data.getParcelableArrayListExtra(RouterList.PhotoSelectActivity.key_result);
            if (result != null) {
                previewImage.addData(result);
            }
        }
    }

    private void doCompress(String[] uploadPaths, final OnCompressListener.OnCompressListenerAdapter listener) {
        CompressManager compressManager = CompressManager.create(this);
        for (String uploadPath : uploadPaths) {
            compressManager.addTask().setOriginalImagePath(uploadPath);
        }
        mPopupProgress.showPopupWindow();
        compressManager.start(new OnCompressListener.OnCompressListenerAdapter() {
            @Override
            public void onSuccess(List<String> imagePath) {
                if (listener != null) {
                    listener.onSuccess(imagePath);
                }
                mPopupProgress.dismiss();
            }

            @Override
            public void onCompress(long current, long target) {
                float progress = (float) current / target;
                mPopupProgress.setProgressTips("正在压缩第" + current + "/" + target + "张图片");
                mPopupProgress.setProgress((int) (progress * 100));
            }

            @Override
            public void onError(String tag) {
                mPopupProgress.dismiss();
                UIHelper.ToastMessage(tag);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (permissionHelper != null)
            permissionHelper.handleDestroy();
    }

    @OnClick(R.id.publish)
    public void onClick() {
        String title = editTitle.getText().toString().trim();
        String content = editContent.getText().toString().trim();

        List<ImageInfo> datas = previewImage.getDatas();
        final boolean hasImage = !ToolUtil.isListEmpty(datas);
        if (mPopupProgress == null) {
            mPopupProgress = new PopupProgress(this);
        }
        String[] uploadTaskPaths;
        if (hasImage) {
            uploadTaskPaths = new String[datas.size()];
            for (int i = 0; i < datas.size(); i++) {
                uploadTaskPaths[i] = datas.get(i).getImagePath();
            }
            doCompress(uploadTaskPaths, new OnCompressListener.OnCompressListenerAdapter() {
                @Override
                public void onSuccess(List<String> imagePath) {
                    if (!ToolUtil.isListEmpty(imagePath)) {
                        ArrayList<File> files = new ArrayList<>();
                        for (int i = 0; i < imagePath.size(); i++) {
                            uploadTaskPaths[i] = imagePath.get(i);
                            File file = new File(imagePath.get(i));
                            files.add(file);
                        }
                        publishArticlesImage(title, content,files);
                    } else {
                        publishArticles(title, content);
                    }
                }
            });
        } else {
            publishArticles(title, content);
        }

    }

    private void publishArticles(String title, String content) {
        HttpParams params = OkHttpManager.getParams();
        params.put("title", title);
        params.put("content", content);
        OkHttpManager.getInstance(this).get(UrlApi.articleInsert, params, new JsonCallback<BaseBean>() {
            @Override
            public void onSuccess(Response<BaseBean> response) {
                if (response != null && response.body() != null){
                    if (response.body().getResultCode() == 0){
                        ToastUtil.makeToast(getBaseContext(),"发布成功！");
                        finish();
                    }else {
                        ToastUtil.makeToast(getBaseContext(),"发布失败！");
                    }
                }
            }
        });

    }

    private void publishArticlesImage(String title, String content, ArrayList<File> files) {
        HttpParams params = OkHttpManager.getParams();
        params.put("title", title);
        params.put("content", content);
        params.putFileParams("file",files);
        OkHttpManager.getInstance(this).get(UrlApi.articleAddArticleImg, params, new JsonCallback<BaseBean>() {
            @Override
            public void onSuccess(Response<BaseBean> response) {

            }
        });
    }
}
